﻿using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OnlineStore.Models;
using OnlineStore.Services;

namespace OnlineStore.Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Authorize(Roles = "Admin")]
    public class ProductController : Controller
    {
        private readonly IProductService _productService;

        public ProductController(IProductService productService)
        {
            _productService = productService;
        }

        public IActionResult Index()
        {
            var products = _productService.GetAllProduct();
            return View(products);
        }

        public IActionResult Details(int id)
        {
            var product = _productService.LoadProductWithDetails(id);
            return View(product);
        }

        public IActionResult Add()
        {
            var model = new Product();
            return View(model);
        }

        public IActionResult Delete(int id)
        {
            var product = _productService.FindProductById(id);
            return View(product);
        }


        [HttpPost]
        public async Task<IActionResult> Add(Product product, List<IFormFile> images)
        {
            if (ModelState.IsValid)
            {
                return View(product);
            }

            if (images == null)
            {
                return View(product);
            }
            
            await _productService.AddProductAsync(product, images);
            return RedirectToAction(nameof(Index));
        }

        [HttpPost]
        public async Task<IActionResult> DeleteProduct(int id)
        {
            await _productService.DeleteProduct(id);
            Content("<script>alert('删除成功！')</script>");
            return RedirectToAction(nameof(Index));
        }


        public IActionResult Update(int id)
        {
            var product = _productService.FindProductById(id);
            return View(product);
        }

        [HttpPost]
        public async Task<IActionResult> Update(Product model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }

            await _productService.UpdateProductAsync(model);
            return RedirectToAction(nameof(Index));
        }
    }
}